import axios from 'axios';
import axiosAdapterUniapp from 'axios-adapter-uniapp'
// 创建axios实例
let instance = axios.create({ timeout: 1000 * 12 ,adapter: axiosAdapterUniapp
});
// 设置post请求头
instance.defaults.headers.post['Content-Type'] =
  'application/json';
// 请求拦截器
instance.interceptors.request.use(
  config => {
    let token = uni.getStorageSync('token')
    if(token) {
      config.headers['Authorization'] = token
    }
    return config;
  },
  error => Promise.error(error)
);
// 响应拦截器
instance.interceptors.response.use(
  // 请求成功
  res => {
    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
    // 否则的话抛出错误
    
    if (res.status === 200) {
		if(res.data.message == '登录已过期，请重新登录'){
			uni.navigateTo({
				url:'/pages/login/loginpwd'
			})
		}
      return Promise.resolve(res.data);
    } else if(res.code == 1403 || res.code == 1401){
		uni.navigateTo({
			url:'/pages/login/loginpwd'
		})
		return Promise.reject(res.data);
	}else if(res.status == 500 && res.message == '登录已过期，请重新登录'){
		console.log('走到这')
		uni.navigateTo({
			url:'/pages/login/loginpwd'
		})
		return Promise.reject(res.data);
	}else {
		uni.showToast({
			title: `${res.message || '请求报错'}`,
			icon: "none"
		})
      return Promise.reject(res.data);
    }
  },
  // 请求失败
  error => {
	  let save = Promise.reject(error.response.data)
      save.then((res)=>{
	  },reason => {
		  console.warn(reason)
		// console.warn(reason.message);
		if(reason.message == '登录已过期，请重新登录'){
			console.log('走到这')
			uni.showToast({
				icon:'none',
				title:'登录已过期，请重新登录',
				success:()=>{
					setTimeout(()=>{
						uni.navigateTo({
							url:'/pages/login/loginpwd'
						})
						uni.removeStorageSync('token');
					},1000)
				}
			})
		}
	  })
     return Promise.reject(error.response.data)
   }
);
export default instance;